import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, register as registerApi } from '@/api/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref('')
  const user = ref(null)
  const isLoggedIn = ref(false)

  // 初始化时检查localStorage并验证token
  const initAuth = async () => {
    console.log('🔄 初始化认证状态...')
    const savedToken = localStorage.getItem('token')
    if (savedToken) {
      console.log('🔍 发现保存的token:', savedToken.substring(0, 20) + '...')
      token.value = savedToken
      try {
        // 验证token有效性，可以通过调用一个需要认证的接口
        const response = await fetch('/api/auth/me', {
          headers: {
            'Authorization': `Bearer ${savedToken}`
          }
        })
        
        if (response.ok) {
          const userData = await response.json()
          if (userData.success) {
            user.value = userData.data
            isLoggedIn.value = true
            console.log('✅ Token验证成功，用户已登录:', user.value)
          } else {
            // token无效，清除
            console.log('❌ Token验证失败，清除token')
            clearAuth()
          }
        } else {
          console.log('❌ Token验证请求失败，清除token')
          clearAuth()
        }
      } catch (error) {
        console.log('❌ Token验证异常，清除token:', error)
        clearAuth()
      }
    } else {
      console.log('📝 未发现保存的token，用户未登录')
    }
  }

  // 清除认证信息
  const clearAuth = () => {
    console.log('🧹 清除认证信息')
    token.value = ''
    user.value = null
    isLoggedIn.value = false
    localStorage.removeItem('token')
  }

  // 登录
  const login = async (credentials) => {
    try {
      console.log('🔐 开始登录请求...', credentials)
      
      const response = await loginApi({
        usernameOrEmail: credentials.username,
        password: credentials.password
      })
      
      console.log('📥 登录响应:', response)
      
      if (response.success) {
        const { token: authToken, user: userInfo } = response.data
        
        // 保存认证信息
        token.value = authToken
        user.value = userInfo
        isLoggedIn.value = true
        localStorage.setItem('token', authToken)
        
        console.log('✅ 登录成功，保存token和用户信息')
        ElMessage.success('登录成功')
        
        // 跳转到首页
        router.push('/')
        
        return response
      } else {
        console.log('❌ 登录失败:', response.message)
        ElMessage.error(response.message || '登录失败')
        throw new Error(response.message || '登录失败')
      }
    } catch (error) {
      console.error('❌ 登录异常:', error)
      const message = error.response?.data?.message || error.message || '登录失败'
      ElMessage.error(message)
      throw error
    }
  }

  // 注册
  const register = async (userInfo) => {
    try {
      console.log('📝 开始注册请求...', userInfo)
      
      const response = await registerApi(userInfo)
      
      console.log('📥 注册响应:', response)
      
      if (response.success) {
        console.log('✅ 注册成功')
        ElMessage.success('注册成功，请登录')
        
        // 跳转到登录页
        router.push('/login')
        
        return response
      } else {
        console.log('❌ 注册失败:', response.message)
        ElMessage.error(response.message || '注册失败')
        throw new Error(response.message || '注册失败')
      }
    } catch (error) {
      console.error('❌ 注册异常:', error)
      const message = error.response?.data?.message || error.message || '注册失败'
      ElMessage.error(message)
      throw error
    }
  }

  // 登出
  const logout = () => {
    console.log('🚪 用户登出')
    clearAuth()
    ElMessage.success('已退出登录')
    router.push('/login')
  }

  return {
    // 状态
    token,
    user,
    isLoggedIn,
    
    // 方法
    initAuth,
    login,
    register,
    logout,
    clearAuth
  }
}) 